package com.huilai.platform.country_platform.service;

import com.huilai.platform.country_platform.core.*;
import com.huilai.platform.country_platform.dto.FeedbackDTO;
import com.huilai.platform.country_platform.dto.RecruitmentDTO;
import com.huilai.platform.country_platform.dto.RecruitmentHasUserDTO;
import com.huilai.platform.country_platform.model.*;
import com.huilai.platform.country_platform.repository.*;
import com.huilai.platform.country_platform.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：洪霓
 * 日期：2023/2/20
 * 注释：
 */
@Service
public class SystemService {

    @Autowired
    SysUserRepository sysUserRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PartyActivitiesReposity partyActivitiesReposity;

    @Autowired
    InformationRecruitmentReposity informationRecruitmentReposity;

    @Autowired
    UserRecruitmentReposity userRecruitmentReposity;

    @Autowired
    VillageCommitteeReposity villageCommitteeReposity;

    @Autowired
    VillageActivitiesReposity villageActivitiesReposity;

    @Autowired
    VillageFeedbackReposity villageFeedbackReposity;

    @Autowired
    FeedbackPersonReposity feedbackPersonReposity;

    @Autowired
    FeedbackBeReposity feedbackBeReposity;

    @Autowired
    AttractionsBuildingReposity attractionsBuildingReposity;

    @Autowired
    AttractionsWaterscapeReposity attractionsWaterscapeReposity;


    public Result login(SysUser sysUser, HttpServletResponse response, HttpSession session) {

        SysUser sysUserByUsername= sysUserRepository.findSysUserByUsername(sysUser.getUsername());
        if (sysUserByUsername == null) {
            return ResultGenerator.genFailResult("用户名错误！");
        } else {
            if (sysUser.getPassword().equals(sysUserByUsername.getPassword())) {
                CookieUtil.set(response, "sysUsername", sysUser.getUsername(), 3600);
                User user = new User(sysUser.getUsername());
                session.setAttribute("user", user);
                return ResultGenerator.genSuccessResult();
            } else {
                return ResultGenerator.genFailResult("密码错误");
            }
        }

    }

    public void logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        System.out.println("dddd");
        Cookie cookie = CookieUtil.get(request, "sysUsername");
        if (cookie != null) {
            CookieUtil.set(response, "sysUsername", null, 0);
        }

        session.setAttribute("user", null);
    }

    public Page<User> toUserinfoListUI(Pageable pageable){
//        查询所有用户信息
        Page<User> userPage = userRepository.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.asc(root.get("id")));
            return null;
        },pageable);
        return userPage;
    }

    public Page<VillageCommittee> toPartyCommitteeListUI(Pageable pageable, String searchName){
//        查询所有党务管理列表
        Page<VillageCommittee> partyCommitteePage = villageCommitteeReposity.findAll((root, query, cb) ->{
            List<String> unitList = new ArrayList<>();
            unitList.add("党政综合办公室");
            unitList.add("党建工作办公室");
            unitList.add("人大办公室");
            unitList.add("纪检监察办公室");
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("name"), "%" + searchName + "%")),
                        (cb.like(root.get("position"), "%" + searchName + "%"))));
            }
            predicates.add(root.get("unit").in(unitList));
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("unit")));
            return null;
        },pageable);
        return partyCommitteePage;
    }

    public Page<PartyActivities> toPartyActivitiesListUI(Pageable pageable, String searchName){
//        查询所有党建活动列表
        Page<PartyActivities> partyActivitiesPage = partyActivitiesReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("title"), "%" + searchName + "%")),
                        (cb.like(root.get("contentType"), "%" + searchName + "%"))));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        return partyActivitiesPage;
    }
    public Page<VillageCommittee> toVillageCommitteeListUI(Pageable pageable, String searchName){
//        查询所有村委管理列表
        Page<VillageCommittee> partyCommitteePage = villageCommitteeReposity.findAll((root, query, cb) ->{
            List<String> unitList = new ArrayList<>();
            unitList.add("公共服务办公室");
            unitList.add("综合治理办公室");
            unitList.add("综合行政执法办公室");
            unitList.add("经济发展办公室");
            unitList.add("应急管理办公室");
            unitList.add("农业农村办公室");
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("name"), "%" + searchName + "%")),
                        (cb.like(root.get("position"), "%" + searchName + "%"))));
            }
            predicates.add(root.get("unit").in(unitList));
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("unit")));
            return null;
        },pageable);
        return partyCommitteePage;
    }
    public Page<VillageActivities> toVillageActivitiesListUI(Pageable pageable, String searchName){
//        查询所有党建活动列表
        Page<VillageActivities> villageActivitiesPage = villageActivitiesReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("title"), "%" + searchName + "%")),
                        (cb.like(root.get("contentType"), "%" + searchName + "%"))));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        return villageActivitiesPage;
    }

    public Page<FeedbackDTO> toVillageFeedbackListUI(Pageable pageable, String searchName){
//        查询所有的民事反馈信息
        Page<VillageFeedback> villageFeedbackPage = villageFeedbackReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("contentTitle"), "%" + searchName + "%")),
                        (cb.like(root.get("contentMain"), "%" + searchName + "%"))));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);

        Page<FeedbackDTO> feedbackDTOPage = villageFeedbackPage.map(villageFeedback -> {
            FeedbackPerson feedbackPerson = null;
            FeedbackBe feedbackBe = null;
            if (villageFeedback.getFeedbackId()!=null){
                feedbackPerson = feedbackPersonReposity.getOne(villageFeedback.getFeedbackId());
                if (villageFeedback.getBeId()!=null){
                    feedbackBe = feedbackBeReposity.getOne(villageFeedback.getBeId());
                    FeedbackDTO feedbackDTO = new FeedbackDTO(
                            villageFeedback.getId(),
                            feedbackPerson.getName(),
                            feedbackPerson.getPostcard(),
                            feedbackPerson.getTelephone(),
                            feedbackPerson.getPolitical(),
                            feedbackPerson.getAddress(),
                            feedbackPerson.getPosition(),
                            feedbackPerson.getComplaintCategory(),
                            feedbackPerson.getComplaintSituation(),
                            feedbackBe.getName(),
                            feedbackBe.getUnit(),
                            feedbackBe.getPosition(),
                            feedbackBe.getLevel(),
                            villageFeedback.getContentTitle(),
                            villageFeedback.getContentCategory() == null?"群众反馈":villageFeedback.getContentCategory(),
                            villageFeedback.getContentMain(),
                            AuditEnum2.getStringByStatus(villageFeedback.getAuditStatus()),
                            TypeEnum.getStringByStatus(villageFeedback.getType())
                    );
                    return feedbackDTO;
                }else{
                    FeedbackDTO feedbackDTO = new FeedbackDTO(
                            villageFeedback.getId(),
                            feedbackPerson.getName(),
                            feedbackPerson.getPostcard(),
                            feedbackPerson.getTelephone(),
                            feedbackPerson.getPolitical(),
                            feedbackPerson.getAddress(),
                            feedbackPerson.getPosition(),
                            feedbackPerson.getComplaintCategory(),
                            feedbackPerson.getComplaintSituation(),
                            null,
                            null,
                            null,
                            null,
                            villageFeedback.getContentTitle(),
                            villageFeedback.getContentCategory() == null?"群众反馈":villageFeedback.getContentCategory(),
                            villageFeedback.getContentMain(),
                            AuditEnum2.getStringByStatus(villageFeedback.getAuditStatus()),
                            TypeEnum.getStringByStatus(villageFeedback.getType())
                    );
                    return feedbackDTO;
                }
            }
            else {
                if (villageFeedback.getBeId()!=null){
                    feedbackBe = feedbackBeReposity.getOne(villageFeedback.getBeId());
                    FeedbackDTO feedbackDTO = new FeedbackDTO(
                            villageFeedback.getId(),
                            "---",
                            "未填写",
                            "未填写",
                            "未填写",
                            "未填写",
                            "未填写",
                            null,
                            null,
                            feedbackBe.getName(),
                            feedbackBe.getUnit(),
                            feedbackBe.getPosition(),
                            feedbackBe.getLevel(),
                            villageFeedback.getContentTitle(),
                            villageFeedback.getContentCategory() == null?"群众反馈":villageFeedback.getContentCategory(),
                            villageFeedback.getContentMain(),
                            AuditEnum2.getStringByStatus(villageFeedback.getAuditStatus()),
                            TypeEnum.getStringByStatus(villageFeedback.getType())
                    );
                    return feedbackDTO;
                }else{
                    FeedbackDTO feedbackDTO = new FeedbackDTO(
                            villageFeedback.getId(),
                            "---",
                            "未填写",
                            "未填写",
                            "未填写",
                            "未填写",
                            "未填写",
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            villageFeedback.getContentTitle(),
                            villageFeedback.getContentCategory() == null?"群众反馈":villageFeedback.getContentCategory(),
                            villageFeedback.getContentMain(),
                            AuditEnum2.getStringByStatus(villageFeedback.getAuditStatus()),
                            TypeEnum.getStringByStatus(villageFeedback.getType())
                    );
                    return feedbackDTO;
                }
            }
        });
        return feedbackDTOPage;
    }

    public Page<RecruitmentHasUserDTO> toRecruitmentListUI(Pageable pageable, String searchName){
        Page<InformationRecruitment> informationRecruitmentPage = informationRecruitmentReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add(cb.or(
                        (cb.like(root.get("company"), "%" + searchName + "%")),
                        (cb.like(root.get("address"), "%" + searchName + "%"))));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        Page<RecruitmentHasUserDTO> recruitmentHasUserDTOPage = informationRecruitmentPage.map(informationRecruitment -> {
            UserRecruitment userRecruitment = userRecruitmentReposity.findUserRecruitmentByRecruitmentId(informationRecruitment.getId());
            String userName = "管理员";
            if (userRecruitment != null){
                User user = userRepository.findUserById(userRecruitment.getUserId());
                userName = user.getUsername();
            }
            RecruitmentHasUserDTO recruitmentHasUserDTO = new RecruitmentHasUserDTO(
                    informationRecruitment.getId(),
                    userName,
                    informationRecruitment.getCompany(),
                    informationRecruitment.getImage(),
                    informationRecruitment.getAddress(),
                    informationRecruitment.getTelephone(),
                    informationRecruitment.getName(),
                    RecruitmentEnum.getStringByStatus(informationRecruitment.getStatus()),
                    AuditEnum.getStringByStatus(informationRecruitment.getAuditStatus()),
                    informationRecruitment.getDescribe(),
                    informationRecruitment.getCreateTime(),
                    informationRecruitment.getUpdateTime()
            );
            return recruitmentHasUserDTO;
        });
        return recruitmentHasUserDTOPage;

    }

    public Page<AttractionsBuilding>toBuildingListUI(Pageable pageable, String searchName){
//        查询所有的乡镇建筑
        Page<AttractionsBuilding> attractionsBuildingPage = attractionsBuildingReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add((cb.like(root.get("name"), "%" + searchName + "%")));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        return attractionsBuildingPage;
    }

    public Page<AttractionsWaterscape>toWaterscapeListUI(Pageable pageable, String searchName){
//        查询所有的海景
        Page<AttractionsWaterscape> attractionsWaterscapePage = attractionsWaterscapeReposity.findAll((root, query, cb) ->{
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add((cb.like(root.get("name"), "%" + searchName + "%")));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        return attractionsWaterscapePage;
    }
}
